package com.thread.interrupt;

import java.util.Calendar;

public class InterruptDemo extends Thread {

	public static void main(String[] args) throws InterruptedException {
		// 创建线程
		InterruptDemo sleep = new InterruptDemo();
		// 启动线程
		sleep.start();

		// 主线程中断5秒钟
		Thread.sleep(5000);
		// sleep子线程被中断
		sleep.interrupt();
	}

	// 为了更容易理解，在打印内容前面加上当前时间
	private String getTime() {
		Calendar rightNow = Calendar.getInstance();
		rightNow.setTimeInMillis(System.currentTimeMillis());
		return rightNow.get(Calendar.HOUR) + ":"
				+ rightNow.get(Calendar.MINUTE) + ":"
				+ rightNow.get(Calendar.SECOND);
	}

	public void run() {
		try {
			// 做一个无限循环，每一秒打印一条信息
			while (true) {
				sleep(1000);
				System.out
						.println(getTime() + "  " + getName() + " Is Running");
			}
		} catch (InterruptedException e) {
			// 被终端以后打印一条信息
			System.out
					.println(getTime() + "  " + getName() + " Is Interrupted");
			return;
		}
	}
}